local lp = game.Players.LocalPlayer
local charactersFolder = workspace:WaitForChild("Characters")
local runService = game:GetService("RunService")

local animationInfo = {}
local isProcessing = false

function getInfo(id)
    local success, info = pcall(function()
        return game:GetService("MarketplaceService"):GetProductInfo(id)
    end)
    if success then
        return info
    end
    return {Name = ""}
end

function pressOneKeyTwice()
    keypress(0x31)
    task.wait(0.05)
    keyrelease(0x31)
    
    task.wait(0.1)
    keypress(0x31)
    keyrelease(0x31)
end

function handleCharacter(character)
    local humanoid = character:FindFirstChild("Humanoid")
    if not humanoid then
        humanoid = character:WaitForChild("Humanoid", 5)
    end
    if not humanoid then return end
    
    local animConn
    animConn = humanoid.AnimationPlayed:Connect(function(track)
        if isProcessing then return end
        
        local animId = track.Animation.AnimationId
        local info = animationInfo[animId]
        if not info then
            local idNum = tonumber(animId:match("%d+"))
            info = getInfo(idNum)
            animationInfo[animId] = info
        end
        
        local localHead = lp.Character and lp.Character:FindFirstChild("Head")
        local targetHead = character:FindFirstChild("Head")
        if localHead and targetHead then
            local distance = (targetHead.Position - localHead.Position).Magnitude
            if distance < 15 then
                local animName = info.Name:lower()
                if animName:match("parry") then
                    isProcessing = true
                    pcall(pressOneKeyTwice)
                    task.wait(0.2)
                    isProcessing = false
                end
            end
        end
    end)
    
    character.AncestryChanged:Connect(function(_, parent)
        if not parent then
            animConn:Disconnect()
        end
    end)
end

local function startLoop()
    local processedChars = {}
    
    while true do
        if not lp or not lp.Character then
            task.wait(1)
            continue
        end
        
        for _, player in pairs(game.Players:GetPlayers()) do
            if player == lp then continue end
            
            local character = charactersFolder:FindFirstChild(player.Name)
            if character and not processedChars[character] then
                handleCharacter(character)
                processedChars[character] = true
                
                character.AncestryChanged:Connect(function(_, parent)
                    if not parent then
                        processedChars[character] = nil
                    end
                end)
            end
        end
        
        task.wait(0.5)
    end
end

task.spawn(startLoop)